<template>
  <view class="authorization container">
    <button class="auth-btn" open-type="getPhoneNumber" @getphonenumber="handleAuthorization">
      一键授权
    </button>
    <view class="auth-explain">
      第三方用户信息授权说明：
      您授权后，小程序开发者将收集您的微信昵称、头像和手机号为您提供相关服务，
      开发者严格按照"《小程序隐私保护指引》处理你的个人信息，如您发现开发者不当处理您的个人信息，可进行投诉。
    </view>
    <view class="end">
      祝您体验愉快！
    </view>
  </view>
</template>

<script setup lang="ts">
import { setAuthorization } from "@/utils/auth";
import { baseURL } from "@/api/request";

// 处理授权
const handleAuthorization = (e: any) => {
  console.log("事件对象 e:", e);
  weChatAuthorization();
  getPhoneNumber(e);
};

// 微信授权
const weChatAuthorization = () => {
  uni.login({
    provider: "weixin",
    onlyAuthorize: true,
    success: async function (event) {
      const { code } = event;
      uni.request({
        url: baseURL + '/ignore/user/login/login?code=' + code,
        method: 'POST',
        success: (res) => {
          const openId = res.data.data.openId;
		  console.log('res==========',res)
          uni.setStorageSync('openId', openId);
          setAuthorization(res.data.data as string);
          uni.getUserInfo({
            provider: 'weixin',
            success: function (info) {
              uni.setStorageSync('USER_INFO', JSON.stringify(info.userInfo));
            }
          });
          uni.switchTab({ url: '/pages/components/n-shopCar' });
        },
        fail: function (err) {
          uni.showToast({ title: '授权失败!', icon: 'error', duration: 1000, mask: true });
        }
      });
    },
    fail: async function (event) {
      uni.showToast({ title: '授权失败!', icon: 'error', duration: 1000, mask: true });
    }
  });
};

// 获取手机号
const getPhoneNumber = (e: any) => {
  console.log(e);
  const detail = e.detail;
  if (detail.errMsg == "getPhoneNumber:ok") {
    console.log("用户同意授权");
    const code = detail.code;
    uni.request({
      url: baseURL + '/ignore/user/phone/getPhoneNumber?code=' + code,
      method: 'POST',
      header: { 'content-type': 'application/json' },
      success: (res: any) => {
        console.log("接口返回数据:", res);
        const userPhone = res.data.data.mobile;
        console.log("mobile:", userPhone);
        const userId = res.data.data.userId;
        console.log("userId:", userId);
        uni.setStorageSync('userId', userId);
        uni.setStorageSync('userPhone', userPhone);
        uni.switchTab({ url: '/pages/components/n-shopCar' });
      },
      fail: (err: any) => {
        uni.showModal({ title: "错误!", content: "网络错误!", showCancel: false });
      }
    });
  } else if (detail.errMsg == "getPhoneNumber:fail") {
    uni.showModal({ title: "提示", content: "用户拒绝了授权", showCancel: false });
  } else {
    uni.showModal({ title: "提示", content: "授权失败，请重试", showCancel: false });
  }
};
</script>

<style scoped lang="scss">
.authorization {
  display: flex;
  flex-direction: column;
  align-items: center;
  .auth-btn {
    margin-top: 50rpx;
    margin-bottom: 50rpx;
    width: 90% !important;
    border-radius: 40rpx;
    background: $uni-primary;
    font-weight: 700;
    color: #fff;
    letter-spacing: 5px;
  }
  .auth-explain {
    padding: 0 40px;
    color: $uni-base-color;
  }
  .end {
    color: $uni-base-color;
  }
}
</style>